package com.party.core.service.crowdfund.impl;

import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.*;
import com.party.core.model.member.MemberAct;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberCopartnerCountService;
import com.party.core.service.member.IMemberCopartnerDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 众筹数据转换接口实现
 * Created by wei.li
 *
 * @date 2017/7/13 0013
 * @time 16:24
 */

@Service
public class ProjectTransferService implements IProjectTransferService {

    @Autowired
    private ISupportService supportService;

    @Autowired
    private ProjectReviseService projectReviseService;

    @Autowired
    private ITargetProjectService targetProjectService;


    @Autowired
    private IActivityService activityService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private ISupportTransferDetailService supportTransferDetailService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private IMemberCopartnerCountService memberCopartnerCountService;

    @Autowired
    private IMemberCopartnerDetailService memberCopartnerDetailService;

    @Autowired
    private ICounterfoilService counterfoilService;

    Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public void transfer(String sourceId, String targetId) {
        // 目标众筹
        DistributorRelation targetDisRelation = this.getDistributorRelation(targetId);
        // 源众筹
        DistributorRelation sourceDisRelation = this.getDistributorRelation(sourceId);


        List<SupportWithMember> list = supportService.findByProjectId(sourceId);
        for (SupportWithMember supportWithMember : list) {
            Support support = supportWithMember;
            support.setProjectId(targetId);
            supportService.update(support);

            // 减去分销数据，删除分销详情
            subDisCount(sourceDisRelation, supportWithMember);

            // 增加分销数据，增加分销详情
            addDisCount(targetDisRelation, supportWithMember);

        }

        //校正数据
        projectReviseService.reviseFavorer(sourceId);
        projectReviseService.reviseFavorer(targetId);

        //校正众筹目标数据
        TargetProject source = targetProjectService.findByProjectId(sourceId);
        TargetProject target = targetProjectService.findByProjectId(targetId);
        projectReviseService.reviseTarget(source.getTargetId());
        projectReviseService.reviseTarget(target.getTargetId());
    }


    /**
     * 众筹转移活动报名表状态维护
     *
     * @param targetProId 目标项目编号
     * @param targetId 目标活动编号
     */
    @Override
    public void projectMemberActStateUpdate(String targetProId,String targetId, String counterfoilId){
        Counterfoil counterfoil = counterfoilService.get(counterfoilId);
        Project tagProject = projectService.get(targetProId);
        float f1 = tagProject.getActualAmount();
        float f2 = counterfoil.getPayment();
        if(f1 == f2){
            MemberAct maobj= memberActService.findByMemberAct(tagProject.getAuthorId(),targetId);
            maobj.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
            maobj.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberActService.update(maobj);
        }
    }

    /**
     * 记录转移的支持者
     *
     * @param targetProId 目标项目id
     * @param transferId 转移表id
     */
    @Override
    public void recordTransferSupporters(String targetProId,String transferId){
        List<SupportWithMember> list = supportService.findByProjectId(targetProId);
        for (SupportWithMember supportWithMember : list) {
            supportTransferDetailService.insert(new SupportTransferDetail(transferId,supportWithMember.getId()));
        }
    }


    /**
     * 根据目标编号找分销者编号
     *
     * @param targetId 目标编号
     * @return 分销者编号
     */
    public DistributorRelation getDistributorRelation(String targetId) {
        DistributorDetail distributorDetail = distributorDetailService.findByTargetId(targetId);
        if (distributorDetail != null) {
            DistributorRelation distributorRelation = distributorRelationService.get(distributorDetail.getDistributorRelationId());
            return distributorRelation;
        }
        return null;
    }

    /**
     * 增加分销数据，增加分销详情
     *
     * @param relation 分销关系
     * @param support  支持者数据
     */
    @Transactional
    public void addDisCount(DistributorRelation relation, SupportWithMember support) {
        if (null != relation) {
            try {
                DistributorDetail distributorDetail = distributorDetailService.get(support.getOrderId(),
                        DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode(), relation.getId());
                if (null == distributorDetail) {
                    distributorDetail = new DistributorDetail();
                    distributorDetail.setTargetId(support.getOrderId());
                    distributorDetail.setDistributorRelationId(relation.getId());
                    distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode());
                    distributorDetailService.insert(distributorDetail);

                    DistributorCount distributorCount = distributorCountService.findByRelationIdLock(relation.getId());

                    float add = BigDecimalUtils.add(distributorCount.getFavorerAmount(), support.getPayment());
                    add = BigDecimalUtils.round(add, 2);
                    distributorCount.setFavorerAmount(add);
                    distributorCount.setFavorerNum(distributorCount.getFavorerNum() + 1);
                    distributorCount.setSalesNum(distributorCount.getSalesNum() + 1);
                    distributorCountService.update(distributorCount);

                    System.out.println("加22222222；" + distributorCount.getFavorerAmount());
                }
            } catch (Exception e) {
                logger.error("增加分销数据，增加分销详情异常", e);
            }
        }
    }

    /**
     * 减去分销数据，删除分销详情
     *
     * @param relation 分销关系
     * @param support  支持者数据
     */
    @Transactional
    public void subDisCount(DistributorRelation relation, SupportWithMember support) {
        if (null != relation) {
            try {
                distributorDetailService.deleteByTargetId(support.getOrderId(), relation.getId());

                DistributorCount distributorCount = distributorCountService.findByRelationIdLock(relation.getId());
                if (null != distributorCount) {
                    float sub = BigDecimalUtils.sub(distributorCount.getFavorerAmount(), support.getPayment());
                    sub = BigDecimalUtils.round(sub, 2);
                    distributorCount.setFavorerAmount(sub);
                    distributorCount.setFavorerNum(distributorCount.getFavorerNum() - 1);
                    distributorCount.setSalesNum(distributorCount.getSalesNum() - 1);
                    distributorCountService.update(distributorCount);

                    System.out.println("减1111111；" + distributorCount.getFavorerAmount());
                }
            } catch (Exception e) {
                logger.error("减去分销数据，删除分销详情异常", e);
            }

            try {
                if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(relation.getType())) {
                    memberCopartnerCountService.updateOrderAnalyzeSub(support.getPayment(), relation.getDistributorId());

                    String formatDate = DateUtils.formatDate(support.getCreateDate(), DateUtils.DATE_PATTERN);
                    String formatToday = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
                    String option = formatToday.equals(formatDate) ? Constant.OPTION_ADD : Constant.OPTION_SUB;

                    memberCopartnerDetailService.updateOrderAnalyzeSub(support.getPayment(), relation.getDistributorId(), option);
                }
            } catch (Exception e) {
                logger.error("subDisCount合伙人统计异常", e);
            }
        }
    }
}
